import threading
from PyQt4 import QtCore, QtGui
import sys
import time
import numpy

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
from matplotlib.figure import Figure
from auxillaries.QtFrame import Ui_Dialog


class QtFrameMatplotlib(QtGui.QMainWindow, Ui_Dialog):
    def __init__(self):
        Ui_Dialog.__init__(self)
      
    def initialize(self,app):

        self.Dialog = QtGui.QDialog()
        self.Dialog.setObjectName("Dialog")
        self.setupUi(self.Dialog)
        
        bg = self.widget.palette().window().color()
        cl = (bg.redF(), bg.greenF(), bg.blueF())

        self.dpi = 100
        self.figure = Figure((6.5, 4.0), dpi=self.dpi, edgecolor=cl, facecolor=cl)
        self.canvas0 = FigureCanvas(self.figure)
        self.canvas0.setParent( self.widget )
        
        self.axes0 = self.figure.add_subplot( 111 )
        self.axes0.grid( True )

        self.t_values = numpy.arange(0,1000,1)
        self.y_values = numpy.zeros(1000)    
            
        self.line0, = self.axes0.plot(self.t_values,self.y_values)
    
        self.axes0.set_ybound(0, 1.1)
        self.axes0.set_xbound(0, 1000)
        self.axes0.set_ylabel('Value')
        self.axes0.set_xlabel('Time in seconds')
        self.axes0.set_xticks(numpy.arange(11)*100)
        self.axes0.set_xticklabels(['0','1', '2', '3', '4', '5', '6','7', '8', '9', '10'])
        
        self.axes1 = self.axes0.twinx()
        self.line1, = self.axes1.plot(self.t_values,self.y_values, 'r')          
        self.axes1.set_ybound(0, 1.1)
        self.axes1.set_ylabel('Validity')
     
        self.mpl_toolbar = NavigationToolbar(self.canvas0, self.widget)     
              
        self.Dialog.show()
        app.exec_()

class worker(threading.Thread):
    def __init__(self, gui):
        threading.Thread.__init__(self)
        self.gui = gui

    def run(self):
        app = QtGui.QApplication(sys.argv)
        self.gui.initialize(app)
   
if __name__ == "__main__":
    ui=QtFrameMatplotlib()
    guiWorker=worker(ui)
    guiWorker.start()
   
    for i in range(10):
        print "main running", " -- ", i
        try:
            ui.label.setText(str(i))
        except:
            print "Mmmh"
        time.sleep(1)
